package com.cos.shop.web.servlet;

import com.cos.shop.common.Const;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * Copyright (C),2021-2022,亚瑟王
 * FileName: BaseServlet
 * Author: saber
 * Date:2022/9/16 17:16
 */
public class BaseServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        try {
            String method = req.getParameter("method");

            Class aClass = this.getClass();

            Method method1 = aClass.getMethod(method, HttpServletRequest.class, HttpServletResponse.class);

            String result = (String) method1.invoke(this, req, resp);

            if (result!=null) {
                if (result.startsWith(Const.FORWARD)) {
                    req.getRequestDispatcher(result.replace(Const.FORWARD,"")).forward(req,resp);
                }else if(result.startsWith(Const.REDIRECT)){
                    resp.sendRedirect(result.replace(Const.REDIRECT,""));
                }else {
                    resp.getWriter().print(result);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            resp.sendRedirect("/error.jsp");
        }

    }
}
